package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@Tag(name = "文件上传模块")
@RequestMapping("/v1/file/")
public class UploadController {

    /**
     * 上传文件功能
     * @param file: 文件对象
     * @return JsonResult
     */
    @PostMapping("upload")
    @Operation(summary = "上传文件功能")
    @ApiOperationSupport(order = 10)
    public JsonResult upload(MultipartFile file) throws IOException {
        //终极目标:把文件保存到服务器的指定目录[d:/files/2025/07/14/0cdc6b2c-001f-40a0-bb11-aa306abc4e3b.jpg]中
        //*****************第1步:处理文件名*********************
        //1.1 原始文件名filename: zly.jpg
        String filename = file.getOriginalFilename();
        //1.2 获取原始文件名的后缀: .jpg
        String suffix = filename.substring(filename.lastIndexOf("."));
        //1.3 生成全球唯一的UUID[处理文件名]: 0cdc6b2c-001f-40a0-bb11-aa306abc4e3b
        UUID uuid = UUID.randomUUID();
        //1.4 拼接文件名: 0cdc6b2c-001f-40a0-bb11-aa306abc4e3b.jpg
        filename = uuid + suffix;

        //*****************第2步:处理路径*************************
        //2.1 自定义日期时间格式的对象: /yyyy/MM/dd/ ---> /2025/07/14/
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //2.2 定义静态资源路径PATH: d:/files
        String dirPath = "d:/files";
        //2.3 创建目录: d:/files/2025/07/14/
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //*****************第3步:保存文件*************************
        String filePath = dirPath + datePath + filename;
        file.transferTo(new File(filePath));

        //服务器端需要把图片的存储路径返回给客户端,用于客户端在浏览器中渲染该图片;
        //d:/files/2025/07/14/0cdc6b2c-001f-40a0-bb11-aa306abc4e3b.jpg
        //前端工程师:http://localhost:8080/2025/07/14/0cdc6b2c-001f-40a0-bb11-aa306abc4e3b.jpg
        return JsonResult.ok(datePath + filename);
    }
}
















